package com.strive.village.controller;


import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.strive.village.common.Result;
import com.strive.village.entity.TbResident;
import com.strive.village.entity.TbVillage;
import com.strive.village.entity.dto.ResidentDto;
import com.strive.village.entity.dto.VillageDto;
import com.strive.village.exception.EasyExcelException;
import com.strive.village.utils.DBExportUtils;
import com.strive.village.utils.DBVillageUploadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author strivePeng
 * @since 2024-04-18
 */
@RestController
@RequestMapping("/sys/village")
public class TbVillageController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(TbVillageController.class);

    /**
     * 分页查询所有乡村信息
     *
     * @param vName
     * @return
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:village:list')")
    public Result getVillageList(String vName) {
        Page<TbVillage> pageData = villageService.page(getPage(), new QueryWrapper<TbVillage>().like(StrUtil.isNotBlank(vName), "village_name", vName));
        return Result.success(pageData);
    }

    /**
     * 根据ID查询乡村信息
     *
     * @param villageId 乡村ID
     * @return 一条乡村信息
     */
    @GetMapping("/info/{villageId}")
    @PreAuthorize("hasAuthority('sys:village:list')")
    public Result getVillageInfo(@PathVariable(name = "villageId") Long villageId) {
        TbVillage village = villageService.getById(villageId);
        return Result.success(village);
    }


    /**
     * 保存一条乡村信息
     *
     * @param village 前端传来的乡村信息
     * @return msg消息
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:village:save')")
    public Result saveVillage(@RequestBody TbVillage village) {
        villageService.save(village);
        return Result.success("添加成功");
    }

    /**
     * 更新一条乡村信息
     *
     * @param village 前端传来的乡村信息
     * @return msg消息
     */
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:village:update')")
    public Result updateVillage(@RequestBody TbVillage village) {
        villageService.updateById(village);
        return Result.success("更新成功");
    }

    /**
     * 删除乡村信息
     *
     * @param villageIds 前端传来的乡村IDs
     * @return msg消息
     */
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('sys:village:delete')")
    public Result deleteVillage(@RequestBody Long[] villageIds) {
        villageService.removeByIds(Arrays.asList(villageIds));
        // 删除关联表 数据库村民表外键自动删除
        return Result.success("删除成功");
    }

    // 文件导出路径
    @Value("${export.file.path}")
    private String exportPath;


    /**
     * 文件导出接口
     *
     * @return 返回导出信息
     */
    @GetMapping("/export")
    public Result exportVillageInfo() {
        // 使用DTO类导出
        try {
            List<TbVillage> villageList = villageService.list();
            if (villageList.isEmpty()) {
                return Result.fail("文件为空");
            } else {
                List<VillageDto> dtoList = new ArrayList<>();
                // 循环读取数据 转化为DTO
                villageList.forEach(r -> {
                    VillageDto dto = new VillageDto();
                    dto.setVillageName(r.getVillageName());
                    dto.setCounty(r.getCounty());
                    dto.setPopulation(r.getPopulation());
                    dto.setProvince(r.getProvince());
                    dto.setEstablishData(r.getEstablishData());
                    dto.setDescription(r.getDescription());
                    dtoList.add(dto);
                });
                DBExportUtils.exportVillageToExcel(dtoList, exportPath);
                return Result.success(MapUtil.builder()
                        .put("filePath", exportPath)
                        .build());
            }
        } catch (EasyExcelException e) {
            logger.error(e.getMessage(), e);
            throw new EasyExcelException(e.getMessage(), e);
        }
    }

    /**
     * 文件导入接口
     *
     * @param file 前段传来的文件
     * @return 返回导出结果
     */
    @PostMapping("/upload")
    public Result importVillageInfo(@RequestBody MultipartFile file) {
        if (file.isEmpty()) {
            return Result.fail("上传文件为空");
        } else {
            try (InputStream inputStream = file.getInputStream()) {
                // 读取文件内容
                EasyExcel.read(inputStream, VillageDto.class, villageUploadUtils).sheet().doRead();
                return Result.success("文件导入成功");
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
                throw new EasyExcelException("文件上传失败", e);
            }
        }
    }
}
